package com.quyunshuo.module.home.manager

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.quyunshuo.module.home.room.dao.StepsDao
import com.quyunshuo.module.home.room.entity.Steps
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@SuppressLint("StaticFieldLeak")
object StepCounterManager {
    // 数据库相关
    private lateinit var stepsDao: StepsDao
    private lateinit var scope: CoroutineScope
    
    // 日期处理
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    private var currentDate: String = dateFormat.format(Date())
    
    // 上下文和传感器相关变量
    private lateinit var context: Context
    private lateinit var sensorManager: SensorManager
    private var stepSensor: Sensor? = null
    
    // 步数数据流
    private var _stepCount = MutableStateFlow(0)
    val stepCount: StateFlow<Int> = _stepCount.asStateFlow()
    
    // 状态变量
    private var isListening = false
    private var lastTotalSteps = 0
    private var lastSaveTime = 0L
    
    // 传感器事件监听器
    private val sensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent?) {
            event?.let {
                if (it.sensor.type == Sensor.TYPE_STEP_COUNTER) {
                    val totalSteps = it.values[0].toInt()
                    Log.d("StepCounter", "onSensorChanged: $totalSteps")
                    handleStepCount(totalSteps)
                }
            }
        }
        
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
            // 不需要处理
        }
    }
    
    /**
     * 初始化计步管理器
     * @param context 应用上下文
     * @param dao Room数据库的StepsDao
     * @param coroutineScope 协程作用域
     */
    fun initialize(context: Context, dao: StepsDao, coroutineScope: CoroutineScope) {
        this.context = context.applicationContext
        this.stepsDao = dao
        this.scope = coroutineScope
        
        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        
        // 初始化当天数据
        initDailyData()
    }
    
    /**
     * 初始化或恢复当天数据
     */
    private fun initDailyData() {
        scope.launch(Dispatchers.IO) {
            try {
                val today = getStartOfDay()
                val todaySteps = stepsDao.queryTodayStep(today)
                
                if (todaySteps != null) {
                    // 恢复已有数据
                    _stepCount.value = todaySteps.stepCount
                    lastTotalSteps = 0 // 重置传感器计数
                    
                    // 尝试从传感器获取当前总步数
                    stepSensor?.let { sensor ->
                        val event = sensorManager.getSensorList(Sensor.TYPE_STEP_COUNTER)?.firstOrNull()
                        event?.let {
                            lastTotalSteps = it.resolution.toInt() // 获取传感器当前值
                        }
                    }
                } else {
                    // 创建新记录
                    val newSteps = Steps(
                        stepCount = 0,
                        date = today
                    )
                    stepsDao.insert(newSteps)
                    _stepCount.value = 0
                    lastTotalSteps = 0
                }
                
                // 检查日期变更（处理跨天情况）
                checkDateChange()
            } catch (e: Exception) {
                Log.e("StepCounter", "初始化数据失败: ${e.message}")
            }
        }
    }
    
    /**
     * 开始监听计步传感器
     */
    fun startListening() {
        if (isListening || stepSensor == null) return
        
        stepSensor?.let {
            sensorManager.registerListener(
                sensorEventListener,
                it,
                SensorManager.SENSOR_DELAY_UI
            )
            isListening = true
        }
    }
    
    /**
     * 停止监听计步传感器
     */
    fun stopListening() {
        if (!isListening) return
        
        sensorManager.unregisterListener(sensorEventListener)
        isListening = false
        saveCurrentSteps()
    }
    
    /**
     * 处理计步传感器返回的步数数据
     * @param totalSteps 传感器返回的总步数
     */
    private fun handleStepCount(totalSteps: Int) {
        // 处理传感器重置情况
        if (totalSteps < lastTotalSteps) {
            lastTotalSteps = 0
        }
        
        // 计算自上次记录以来的新增步数
        val stepsSinceLast = totalSteps - lastTotalSteps
        if (stepsSinceLast > 0) {
            lastTotalSteps = totalSteps
            
            // 更新当天步数
            _stepCount.value += stepsSinceLast
            
            // 检查日期变更
            checkDateChange()
            
            // 更新数据库
            updateDailySteps()
        }
    }
    
    /**
     * 检查日期变更
     */
    private fun checkDateChange() {
        val today = dateFormat.format(Date())
        
        if (today != currentDate) {
            scope.launch(Dispatchers.IO) {
                try {
                    // 保存前一天的数据
                    saveCurrentSteps()
                    
                    // 创建新记录
                    val newDate = getStartOfDay()
                    val newSteps = Steps(
                        stepCount = 0,
                        date = newDate
                    )
                    stepsDao.insert(newSteps)
                    
                    // 重置状态
                    currentDate = today
                    _stepCount.value = 0
                    lastTotalSteps = 0
                    
                    Log.d("StepCounter", "新的一天开始: $today")
                } catch (e: Exception) {
                    Log.e("StepCounter", "创建新记录失败: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 更新数据库中的当天步数
     */
    private fun updateDailySteps() {
        scope.launch(Dispatchers.IO) {
            try {
                val today = getStartOfDay()
                val todaySteps = stepsDao.queryTodayStep(today) ?: return@launch
                
                // 更新步数
                todaySteps.stepCount = _stepCount.value
                stepsDao.update(todaySteps)
                
                // 控制保存频率：每分钟最多保存一次
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastSaveTime > 60000) {
                    lastSaveTime = currentTime
                }
            } catch (e: Exception) {
                Log.e("StepCounter", "更新步数失败: ${e.message}")
            }
        }
    }
    
    /**
     * 保存当前步数到数据库
     */
    private fun saveCurrentSteps() {
        scope.launch(Dispatchers.IO) {
            try {
                val today = getStartOfDay()
                val todaySteps = stepsDao.queryTodayStep(today) ?: return@launch
                
                todaySteps.stepCount = _stepCount.value
                stepsDao.update(todaySteps)
            } catch (e: Exception) {
                Log.e("StepCounter", "保存步数失败: ${e.message}")
            }
        }
    }
    
    /**
     * 重置当天步数计数器
     */
    fun resetDailyStepCount() {
        scope.launch(Dispatchers.IO) {
            try {
                val today = getStartOfDay()
                val todaySteps = stepsDao.queryTodayStep(today) ?: return@launch
                
                todaySteps.stepCount = 0
                stepsDao.update(todaySteps)
                
                _stepCount.value = 0
                lastTotalSteps = 0
            } catch (e: Exception) {
                Log.e("StepCounter", "重置步数失败: ${e.message}")
            }
        }
    }
    
    /**
     * 检查设备是否支持计步传感器
     */
    fun isSensorAvailable(): Boolean {
        return stepSensor != null
    }
    
    /**
     * 获取当天开始时间（00:00:00）
     */
    private fun getStartOfDay(): Date {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.time
    }
}